using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using JTC.MiniCommerce.Store;
using JTC.MiniCommerce.Core;

namespace JTC.MiniCommerce.Web.paypal {
  public partial class pdthandler : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
      //TODO: CMC - Add PDT Logging
      string transactionId = Request.QueryString["tx"];
      string orderId = Request.QueryString["cm"];
      
      if(transactionId.IndexOf(",") > -1) {
        transactionId = transactionId.Substring(0, transactionId.IndexOf(",", 0));
        transactionId = HttpUtility.UrlDecode(transactionId);
      }
      if(orderId.IndexOf(",") > -1) { 
        orderId = orderId.Substring(0, orderId.IndexOf(",", 0));
        orderId = HttpUtility.UrlDecode(orderId);
      }
      //Response.Write(transactionId + "<BR>");
      //Response.Write(orderId + "<BR>");

      string response = Synchronize(transactionId);
      if(response.StartsWith("SUCCESS")) {
        string grossAmt = GetPDTValue(response, "mc_gross");
        decimal grossAmount = 0;
        decimal.TryParse(grossAmt, out grossAmount);
        OrderController orderController = new OrderController();
        Guid orderGuid = new Guid(orderId);
        Order order = orderController.FetchOrder(orderGuid);
        if(order.OrderId > 0) {
          Transaction transaction = OrderController.CommitStandardTransaction(order, transactionId, grossAmount);
          Response.Redirect(string.Format("~/receipt.aspx?tid={0}", transaction.TransactionId), true);
        }
      }
    }

    private string GetPDTValue(string pdt, string key) {
      string[] keys = pdt.Split('\n');
      string thisVal = "";
      string thisKey = "";
      foreach(string s in keys) {
        string[] bits = s.Split('=');
        if(bits.Length > 1) {
          thisVal = bits[1];
          thisKey = bits[0];
          if(thisKey.ToLower().Equals(key))
            break;
        }
      }
      return thisVal;
    }

    private string Synchronize(string transactionId) {
      string response = OrderController.Synchronize(transactionId);
      return response;
    }
  }
}
